namespace SimpleWebServices.Web
{
    using System.Globalization;
    using System.Text;
    using System.Xml.Serialization;
    using SimpleWebServices.Configuration;

    [XmlRoot("google")]
    public sealed class GoogleAnalytics
    {
        private const string _script = "<script type=\"text/javascript\">"
            + "var gaJsHost = ((\"https:\" == document.location.protocol) ? \"https://ssl.\" : \"http://www.\");"
            + "document.write(unescape(\"%3Cscript src='\" + gaJsHost + \"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E\"));"
            + "</script>"
            + "<script type=\"text/javascript\">"
            + "try {{"
            + "var pageTracker = _gat._getTracker(\"{0}\");"
            + "{1}"
            + "pageTracker._trackPageview();"
            + "}} catch(err) {{}}</script>";

        [XmlAttribute("domain")]
        public string Domain
        {
            get;
            set;
        }

        [XmlAttribute("tracker")]
        public string Tracker
        {
            get;
            set;
        }

        public static implicit operator string(GoogleAnalytics obj)
        {
            return object.ReferenceEquals(null, obj) ? null : obj.ToString();
        }

        public override string ToString()
        {
            string domain = string.IsNullOrEmpty(this.Domain) ? string.Empty : string.Concat("pageTracker._setDomainName(\"", this.Domain, "\");");
            
            return string.Format(CultureInfo.InvariantCulture, _script, this.Tracker, domain);
        }
    }
}